# coding=utf-8
# encoding=utf-8

import DataBase.Model as model
import DataBase.DAL as dal
import time


def main():
    while True:
        allAcInfo = dal.GetAcInfoAll()
        for singleAcInfo in allAcInfo:
            if isinstance(singleAcInfo, model.ACInfo):
                dal.updateAcStatus(query_ac_status(singleAcInfo.DeviceAddress))
                set_all_ctrl()
                time.sleep(0.5)
    # acstatusModel = model.ACStatus(DeviceAddress=20)
    # acstatusModel = acstatusModel.get_ac_status()
    # print(acstatusModel.Dwind)
    # print(acstatusModel.Aoc)


def query_ac_status(deviceAddress):
    acStatus = model.ACStatus(DeviceAddress=deviceAddress)
    newAcStatus = acStatus.get_ac_status()
    oldAcStatus = dal.GetAcStatusByDeviceAdd(deviceAddress)
    if isinstance(oldAcStatus, model.ACStatus):
        if oldAcStatus.compare_new_status(newAcStatus):  # 新旧数据存在差异！
            newAcStatus.Aoctime = newAcStatus.Updatetime
        else:
            newAcStatus.Aoctime = oldAcStatus.Aoctime
    else:
        newAcStatus.Aoctime = newAcStatus.Aoctime
    return newAcStatus


def set_all_ctrl():
    for singleCtrlCmd in dal.GetCrlSending():
        acInfo = dal.GetAcInfoByDeviceId(singleCtrlCmd)
        singleCtrlCmd.set_ctrl_2_reg(acInfo=acInfo)
        dal.updateAcCtrl(singleCtrlCmd)
        dal.updateAcStatus(query_ac_status(acInfo.DeviceAddress))


if __name__ == '__main__':
    main()
    # for singleCtrlCmd in dal.GetCrlSending():
    #     acInfo = dal.GetAcInfoByDeviceId(singleCtrlCmd)
    #     print(singleCtrlCmd.set_ctrl_2_reg(acInfo=acInfo))
    #     dal.updateAcCtrl(singleCtrlCmd)

    #
    # for i in range(1, 41):
    #     acstatusModel = model.ACStatus(DeviceAddress=i)
    #     acstatusModel = acstatusModel.get_ac_status()
    #     acstatusModel.Aoctime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
    #     acstatusModel.Updatetime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
    #     dal.insert(acstatusModel)


